package org.gaaidou.ptarmigan.springboot.core.serialize.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.gaaidou.ptarmigan.springboot.core.BaseEnum;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

@Slf4j
public class EnumConverter extends JsonDeserializer<Enum<?>> {
    @Override
    public Enum<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        Class<?> currFieldClazz = BeanUtils.findPropertyType(jp.currentName(), jp.getCurrentValue().getClass());
        if (BaseEnum.class.isAssignableFrom(currFieldClazz)) {
            BaseEnum<?>[] enumConstants = (BaseEnum<?>[]) currFieldClazz.getEnumConstants();
            for (BaseEnum<?> enumConstant : enumConstants) {
                if (enumConstant.getValue().toString().equals(jp.getValueAsString())) {
                    return (Enum<?>) enumConstant;
                }
            }
        } else {
            log.warn("Type {} is not a subclass of BaseEnum, please do not annotate it with @JsonDeserialize (using = BaseEnumDeserializer.class).", currFieldClazz);
        }

        return null;
    }
}
